package com.husk.leetcode.tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * <p>
 * 404. 左叶子之和
 * https://leetcode-cn.com/problems/sum-of-left-leaves/
 * </p>
 *
 * @author hushunke@sm.vvip-u.com
 * @since 2021/3/23
 */
public class LeftLeavesSum {

    public int sumOfLeftLeaves(TreeNode root) {
        return this.dfs(root);
    }

    /**
     * 深度优先
     *
     * @param node
     * @return
     */
    public int dfs(TreeNode node) {
        int ans = 0;
        if (node == null) {
            return ans;
        }
        if (node.left != null) {
            ans += isLeafNode(node.left) ? node.left.val : this.dfs(node.left);
        }
        if (node.right != null) {
            ans += this.dfs(node.right);
        }
        return ans;
    }

    public boolean isLeafNode(TreeNode node) {
        return node.left == null && node.right == null;
    }

    /**
     * 广度优先
     *
     * @param root
     * @return
     */
    public int sumOfLeftLeaves2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int ans = 0;
        while (!queue.isEmpty()) {
            TreeNode treeNode = queue.poll();
            if (treeNode.left != null) {
                if (this.isLeafNode(treeNode.left)) {
                    ans += treeNode.left.val;
                } else {
                    queue.add(treeNode.left);
                }
            }
            if (treeNode.right != null) {
                if (!this.isLeafNode(treeNode.right)) {
                    queue.add(treeNode.right);
                }
            }
        }
        return ans;
    }


}
